import utime
from machine import I2C,Pin,SPI,PWM
import machine
import st7789
import ds1307
import network
import urequests
import ujson
import gc

'''***********************************'''
'''LED程序准备'''
'''***********************************'''

G13=Pin(13)
G12=Pin(12)
G13.init(Pin.OUT) #初始化 13 号引脚为输出模式
G12.init(Pin.OUT) #初始化 12 号引脚为输出模式
i2c = I2C(1, sda=Pin(0), scl=Pin(1), freq=100000)
i2cAddress = i2c.scan()
print(i2cAddress[0])


'''****************************'''
'''初始化'''
'''****************************'''

spi = SPI(0, baudrate=40000000, polarity=1, phase=0, bits=8, endia=0, sck=Pin(6), mosi=Pin(8))
display = st7789.ST7789(spi, 240, 240, reset=Pin(11, func=Pin.GPIO, dir=Pin.OUT), dc=Pin(7, func=Pin.GPIO, dir=Pin.OUT))
display.init()  #屏幕初始化页面
utime.sleep(2)
display.fill(st7789.color565(0,0,0))


'''**************************************'''
'''光强数据读取显示'''
'''**************************************'''

BH1750_CMD_POWERDOWN        = 0x0
BH1750_CMD_POWERON          = 0x1
BH1750_CMD_RESET            = 0x7
BH1750_CMD_H_RESOLUTION     = 0x10
BH1750_CMD_H_RESOLUTION2    = 0x11
BH1750_CMD_L_RESOLUTION     = 0x13
BH1750_CMD_ONETIME_H        = 0x20
BH1750_CMD_ONETIME_H2       = 0x21
BH1750_CMD_ONETIME_L        = 0x23
BH1750_I2C_ADD  = 0x23

buf=bytearray(1)
buf[0]=BH1750_CMD_H_RESOLUTION
i2c.write(BH1750_I2C_ADD,buf)
utime.sleep_ms(200)


'''*****************************'''
'''处理时钟模块'''
'''*****************************'''

ds = ds1307.DS1307(i2c)
ds.set_halt(0)  # 运行指令
print(ds.set_time([2022,7,14,4,9,48,0])) #设定时间


'''****************************'''
'''舵机初始化'''
'''****************************'''
pwm = PWM(0, Pin(10),freq=0,duty=80)


'''****************************'''
'''循环'''
'''****************************'''

while True:
    ''''*********************************'''
    '''联网上传'''
    '''**********************************'''
    def connectWIFI():
        print('Connecting wifi...')
        sta_wlan = network.WLAN(network.STA_IF)
        sta_wlan.active(True)
        sta_wlan.connect('lovestudy', 'Rxb20021206', security=network.AUTH_PSK)
        while(sta_wlan.config() == '0.0.0.0'):
            utime.sleep(1)
        print('Connected...')
    connectWIFI()

    def connectWIFI():
        print('Connecting wifi...')
        sta_wlan = network.WLAN(network.STA_IF)
        sta_wlan.active(True)
        sta_wlan.connect('lovestudy', 'Rxb20021206', security=network.AUTH_PSK)
        while(sta_wlan.config() == '0.0.0.0'):
            utime.sleep(1)
        print('Connected...')
    connectWIFI()
    url="http://post.blackwalnut.zucc.edu.cn/thingswise/idos/jets/streams/dev/32101083/smartfishtank___BH1750.BH1750_input_json"
    headers = {
        "content-type": "application/json",
    }
    formData = {
        'data':{
            "Case": "LightIntensity",
            "Sensor": "BH1750"
        },
        'auth':{
            'user': 'ppc',
            'password': 'rxb20021206'
        }
    }
    '''********************************'''


    buf = i2c.read(BH1750_I2C_ADD,2)  # 对读取到光转换
    Light = buf[0] * 256 + buf[1]
    print(Light)
    data=ds.get_time()
    print(data)
    display.fill(st7789.color565(0,0,0))
    display.draw_string(0, 0, 'Light: %.2f' % (Light), color=st7789.color565(66, 133, 244), bg=st7789.color565(66, 133, 244), size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
    display.draw_string(0, 120, 'Time: %s' % (data,), color=st7789.color565(66, 133, 244), bg=st7789.color565(66, 133, 244), size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
    
    if(Light<=50): #根据光强度决定G1电平控制LED灯亮与灭
        G13.on()
    else:
        G13.off()
    t1='(8,0)'
    t2='(20,0)'
    if data is t1:
        pwm.freq(2000)
        utime.sleep_ms(810)
        pwm.freq(0)
    elif data is t2:
        pwm.freq(2000)
        utime.sleep_ms(810)
        pwm.freq(0)

    try:
        Light_1=Light
        formData['data']['Light'] = Light_1
        res = urequests.post(url, data=ujson.dumps(formData),
                headers=headers)
        print(res.status_code)
        print(res.text)
    except Exception as err:
        print(err)
    gc.collect()

    utime.sleep(1)
